package com.example.demo.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.example.demo.mapper.SysLogMapper;
import com.example.demo.model.converter.SysLogConverter;
import com.example.demo.model.core.PageVo;
import com.example.demo.model.entity.SysLog;
import com.example.demo.model.form.LogForm;
import com.example.demo.model.query.LogQuery;
import com.example.demo.model.vo.LogVO;
import com.example.demo.service.SysLogService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 系统日志表(SysLog)表服务实现类
 *
 * @author makejava
 * @since 2025-11-09 17:36:07
 */
@Service
public class SysLogServiceImpl implements SysLogService {

    @Autowired
    private SysLogMapper sysLogMapper;
    @Autowired
    private SysLogConverter sysLogConverter;

    @Override
    public void add(LogForm form) {
        SysLog entity = sysLogConverter.toEntity(form);
        sysLogMapper.insert(entity);
    }

    @Override
    public void update(LogForm form) {
        SysLog entity = sysLogConverter.toEntity(form);
        sysLogMapper.update(entity);
    }

    @Override
    public void delete(List<String> ids) {
        sysLogMapper.deleteBatchByIds(ids);
    }

    @Override
    public PageVo<LogVO> page(LogQuery query) {
        QueryWrapper wrapper = QueryWrapper.create().like(SysLog::getContent, query.getKeywords(), StrUtil.isNotEmpty(query.getKeywords()));
        if (CollectionUtil.isNotEmpty(query.getCreateTime())) {
            wrapper.between(SysLog::getCreateTime, query.getCreateTime().get(0), query.getCreateTime().get(1));
        }
        wrapper.orderBy(SysLog::getCreateTime, false);
        Page<SysLog> page = sysLogMapper.paginate(query.getPageNum(), query.getPageSize(), wrapper);
        PageVo<SysLog> pageVo = new PageVo<>();
        pageVo.setList(page.getRecords());
        pageVo.setTotal(page.getTotalRow());
        return sysLogConverter.toPageVo(pageVo);
    }

    @Override
    public LogForm form(String id) {
        SysLog entity = sysLogMapper.selectOneById(id);
        Assert.notNull(entity, "系统日志不存在");
        return sysLogConverter.toForm(entity);
    }
}
